import { apiClient, apiRoutes } from "../../utils/api";

Page({
  data: {
    devices: []
  },

  onLoad(options) {
    apiClient.get(apiRoutes.devices)
      .then((res) => {
        this.setData({ devices: res.data })
      })
      .catch((err) => {
        console.error('获取设备数据失败:', err);
        wx.showToast({
          title: '获取设备数据失败，请稍后重试',
          icon: 'none'
        });
      });
  },

  handleConfirm: function (e) {
    const {id,index} = e.currentTarget.dataset;
    const lower_limit = this.data.devices[index].lower_limit;
    const upper_limit = this.data.devices[index].upper_limit;
    if(lower_limit < upper_limit){
      // console.log("确认按钮点击，设备ID:", id);
      // 这里可以添加保存逻辑
      const url = apiRoutes.devices+id+'/'
      console.log(url,lower_limit,upper_limit)
      apiClient.patch(url, {"lower_limit":lower_limit, "upper_limit":upper_limit}).then(res=>{
        if(res.statusCode == 200){
          wx.showToast({
            title: '修改成功',
          })
      }
      })
    } else {
      wx.showToast({
        title: '下限需小于上限',
        icon:'error'
      })
    }
  },

  // 处理输入框内容变化
  onInputChange(e) {
    const {field, id} = e.currentTarget.dataset
    const updated_devices = this.data.devices.map((device, i)=>{
      if(id == device.id){
        device[field] = e.detail.value
      }
      return device
    })
    this.setData({devices:updated_devices})
    // console.log(this.data.devices)
  },

});